package com.dong.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;

import org.springframework.stereotype.Component;


import java.util.Date;

/**
 * @author admin
 * @version 1.0.0
 * @ClassName JwtUtils.java
 * @Description TODO
 * @createTime 2022年05月24日 09:01:00
 */
@Data
@Component
@ConfigurationProperties(prefix = "dong.jwt")
public class JwtUtils {


    private long expire;
    private String secret;
    private String header;



    /**
     * 生成jwt
     * @param username
     * @return
     */
    public  String generateToken(String username){
        Date nowDate = new Date();
        Date expireDate = new Date(nowDate.getTime() + 1000 * expire);
        return Jwts.builder()
                .setHeaderParam("type","JWT")
                .setSubject(username)
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS256, secret)
                .compact();
    }
//解析jwt
    public Claims getClaimByToken(String token){
        try {
            return Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e){
            return null;
        }
    }
    //jwt是否过期
    public boolean isTokenExpired(Claims claims){
        return claims.getExpiration().before(new Date());
    }
}
